<template>
  <el-card>
    <template #header>
      <div>useInfiniteScroll</div>
    </template>
    <el-descriptions>
      <el-descriptions-item label="返回一个对象，其中包含以下属性：">
        <li>data: service 返回的数据，其中的 list 属性为聚合后数据</li>
        <li>loading: 是否正在进行首次请求</li>
        <li>loadingMore: 是否正在进行更多数据请求</li>
        <li>noMore: 是否没有更多数据了，配置 options.isNoMore 后生效</li>
        <li>
          loadMore: 加载更多数据，会自动捕获异常，通过 options.onError 处理
        </li>
        <li>
          loadMoreAsync: 加载更多数据，与 loadMore 行为一致，但返回的是
          Promise，需要自行处理异常
        </li>
        <li>
          reload: 加载第一页数据，会自动捕获异常，通过 options.onError 处理
        </li>
        <li>
          reloadAsync: 加载第一页数据，与 reload 行为一致，但返回的是
          Promise，需要自行处理异常
        </li>
        <li>mutate: 直接修改 data</li>
        <li>cancel: 忽略当前 Promise 的响应</li>
      </el-descriptions-item>
    </el-descriptions>
    <el-button @click="() => reload()" style="margin-bottom: 8px">
      Reset
    </el-button>
    <p v-if="loading" />
    <div class="item" v-for="item in data?.list" :key="item" style="">
      {{ item }}
    </div>
    <div style="margin-top: 8px">
      <el-button
        v-if="data?.nextId"
        type="button"
        @click="() => loadMore()"
        :disabled="loadingMore"
      >
        {{ loadingMore ? "Loading more..." : "Click to load more" }}
      </el-button>
      <p v-else><span v-if="!data?.nextId">No more data</span></p>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
  import { useInfiniteScroll } from "vue-hooks-plus";

  // import { useInfiniteScroll } from "@vueuse/core";

  interface Result {
    list: string[];
    nextId: string | undefined;
  }

  const resultData = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "11",
    "12",
    "13",
  ];

  function getLoadMoreList(
    nextId: string | undefined,
    limit: number
  ): Promise<Result> {
    let start = 0;
    if (nextId) {
      start = resultData.findIndex((i) => i === nextId);
    }
    const end = start + limit;
    const list = resultData.slice(start, end);
    const nId = resultData.length >= end ? resultData[end] : undefined;
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list,
          nextId: nId,
        });
      }, 1000);
    });
  }

  const { data, loading, loadMore, loadingMore, reload } = useInfiniteScroll(
    (d) => getLoadMoreList(d?.nextId, 4)
  );
</script>

<style lang="scss" scoped>
  .item {
    padding: 12px;
    border: 1px solid #000;
    background-color: pink;
    text-align: center;
  }
</style>
